﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;

namespace S2_Xxxx_XxxNetApi
{
    public class FlowTypeName
    {
        public static string flowsave = "flowsave";
        public static string flowsubmit = "flowsubmit";
        public static string noflowsave = "noflowsave";
        public static string AdminSave = "AdminSave";
    }

    public class FormExtensions
    {
        //public static string ApiUrl { get; set; }


        public static void SaveLogs(string ApiUrl, string applicationname, string functionname, string inputparames, string outputparames, string remark)
        {
            string formcode = "46e330066478753e";
            string dataid = Guid.NewGuid().ToString();
            Dictionary<string, string> dic = new Dictionary<string, string>();
            dic["应用名称"] = applicationname;
            dic["方法名称"] = functionname;
            dic["输入参数"] = inputparames;
            dic["输出参数"] = outputparames;
            dic["备注"] = remark;
            GetFormLayoutForSave(ApiUrl, formcode, dataid, dic, "", FlowTypeName.noflowsave);
        }

        public static string SaveFormInfo(string ApiUrl, string FormData, string DataId, string FormCode, string creatuserid, string typeName)
        {

            string buttonType = "";
            switch (typeName)
            {
                case "flowsave": { buttonType = "S2Cloud.SmartFlow.Sheet.TempSaveDataButton,S2Cloud.SmartFlow"; } break;
                case "flowsubmit": { buttonType = "S2Cloud.SmartFlow.Sheet.SubmitDataButton,S2Cloud.SmartFlow"; } break;
                case "noflowsave": { buttonType = "S2Cloud.SmartFlow.Sheet.SaveDataButton,S2Cloud.SmartFlow"; } break;
                default: { buttonType = "S2Cloud.SmartFlow.Sheet.TempSaveDataButton,S2Cloud.SmartFlow"; } break;
            }
            HttpClient client = new HttpClient();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            string url = ApiUrl + "/api/Form/SaveFormInfo";
            client.DefaultRequestHeaders.Add("UserId", creatuserid);
            JArray arrylist = JsonConvert.DeserializeObject<JArray>(FormData);
            JObject jsobject = new JObject();
            jsobject["$type"] = buttonType;
            jsobject["DataId"] = DataId;
            jsobject["FormCode"] = FormCode;
            jsobject["IsOriginate"] = true;
            jsobject["UserId"] = creatuserid;
            jsobject["FormData"] = arrylist;
            var response = client.PostAsJsonAsync(url, jsobject).Result;
            if (!response.IsSuccessStatusCode)
            {
                //Response.Write(string.Format("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase));
            }
            var result = response.Content.ReadAsStringAsync().Result;
            var json = JsonConvert.DeserializeObject<JObject>(result);
            return "状态：" + json["Status"].ToString() + ";其他信息内容:" + json["Message"].ToString();
        }


        public static string submitForm_edit(string ApiUrl, string FormData, string DataId, string FormCode, string creatuserid, string instanceid, string typeName)
        {

            string buttonType = "";
            string url = "";
            if (creatuserid == "")
            {
                creatuserid = "18f923a7-5a5e-426d-94ae-a55ad1a4b239";
            }
            switch (typeName)
            {
                case "flowsave": { buttonType = "S2Cloud.SmartFlow.Sheet.TempSaveDataButton,S2Cloud.SmartFlow"; } break;
                case "flowsubmit": { buttonType = "S2Cloud.SmartFlow.Sheet.SubmitDataButton,S2Cloud.SmartFlow"; } break;
                case "noflowsave": { buttonType = "S2Cloud.SmartFlow.Sheet.SaveDataButton,S2Cloud.SmartFlow"; } break;
                case "AdminSave": { buttonType = "S2Cloud.SmartFlow.Sheet.AdminSaveDataButton,S2Cloud.SmartFlow"; } break;
                default: { buttonType = "S2Cloud.SmartFlow.Sheet.TempSaveDataButton,S2Cloud.SmartFlow"; } break;
            }
            HttpClient client = new HttpClient();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            client.DefaultRequestHeaders.Add("UserId", creatuserid);

            url = ApiUrl + "/api/Workflow/GetWorkItemScene";
            JObject jsobjectbefore = new JObject();
            jsobjectbefore["DataId"] = DataId;
            jsobjectbefore["FormCode"] = FormCode;
            jsobjectbefore["CardType"] = 0;
            jsobjectbefore["UserId"] = creatuserid;
            jsobjectbefore["FlowId"] = instanceid;
            var responsebefore = client.PostAsJsonAsync(url, jsobjectbefore).Result;
            var resultbefore = responsebefore.Content.ReadAsStringAsync().Result;
            var jsonbefore = JsonConvert.DeserializeObject<JObject>(resultbefore);

            string WorkItemId = jsonbefore["Result"]["WorkItemId"].ToString();
            string WorkflowVersion = jsonbefore["Result"]["WorkflowVersion"].ToString();

            url = ApiUrl + "/api/Form/SaveFormInfo";

            JArray arrylist = JsonConvert.DeserializeObject<JArray>(FormData);
            JObject jsobject = new JObject();
            jsobject["$type"] = buttonType;
            jsobject["DataId"] = DataId;
            jsobject["WorkItemId"] = WorkItemId;
            jsobject["FlowId"] = instanceid;
            jsobject["WorkflowVersion"] = WorkflowVersion;
            jsobject["FormCode"] = FormCode;
            jsobject["IsOriginate"] = false;
            jsobject["UserId"] = creatuserid;
            jsobject["FormData"] = arrylist;
            var response = client.PostAsJsonAsync(url, jsobject).Result;
            if (!response.IsSuccessStatusCode)
            {
                //Response.Write(string.Format("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase));
            }
            var result = response.Content.ReadAsStringAsync().Result;
            var json = JsonConvert.DeserializeObject<JObject>(result);
            return "状态：" + json["Status"].ToString() + ";其他信息内容:" + json["Message"].ToString();
        }

        public static string GetFormLayoutForSave(string ApiUrl, string formcode, string dataid, Dictionary<string, string> dics, string creatuserid, string typeName, string formType = "NEW")
        {
            string sql = "";
            string instanceid = "";
            if (creatuserid == "")
            {
                creatuserid = "18f923a7-5a5e-426d-94ae-a55ad1a4b239";
            }
            JArray datas = new JArray();
            foreach (string _Key in dics.Keys)
            {
                JObject data1 = new JObject();
                data1["key"] = _Key;
                data1["value"] = dics[_Key];
                datas.Add(data1);
            }

            using (HttpClient client = new HttpClient())
            {
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                string url = ApiUrl + "/api/Form/GetFormLayout/" + formcode;
                client.DefaultRequestHeaders.Add("UserId", creatuserid);
                var response = client.GetAsync(url).Result;
                var result = response.Content.ReadAsStringAsync().Result;
                var json = JsonConvert.DeserializeObject<dynamic>(result);
                List<dynamic> result1 = JsonConvert.DeserializeObject<List<dynamic>>(json["Result"].Fields.ToString());
                JArray arrylist = new JArray();
                foreach (var item in datas)
                {
                    string name = item["key"].ToString();
                    if (name.ToLower().IndexOf("_id") == -1)
                    {
                        dynamic infoitem = result1.Where(p => p.title == name).FirstOrDefault();
                        if (infoitem == null)
                        {
                            throw new Exception("无法在表单中找到对应：" + name + "字段，请核对");
                        }
                        string code = infoitem.code;
                        string componentKey = infoitem.componentKey;

                        JObject dataitem = new JObject();
                        dataitem["ComponentKey"] = componentKey;
                        dataitem["Key"] = code;
                        dataitem["Value"] = item["value"].ToString();
                        arrylist.Add(dataitem);
                    }
                    else
                    {
                        name = name.ToLower().Replace("_id", "");
                        dynamic infoitem = result1.Where(p => p.title == name).FirstOrDefault();
                        if (infoitem == null)
                        {
                            throw new Exception("无法在表单中找到对应：" + name + "字段，请核对");
                        }
                        string code = infoitem.code;
                        string componentKey = infoitem.componentKey;

                        JObject dataitem = new JObject();
                        dataitem["ComponentKey"] = componentKey;
                        dataitem["Key"] = code + "_Id";
                        dataitem["Value"] = item["value"].ToString();
                        arrylist.Add(dataitem);
                    }
                }
                if (dics.Keys.Where(p => p == "EmployeeNumber").Count() == 0)
                {
                    sql = "SELECT `employeeNumber` FROM  t_user where objectid='" + creatuserid + "'";
                    string employeeNumber = MySqlHelper.ExecuteScalar(CommandType.Text, sql, null).ToString();
                    JObject data1 = new JObject();
                    data1["Key"] = "EmployeeNumber";
                    data1["Value"] = employeeNumber;
                    data1["ComponentKey"] = "DefaultComponent";
                    arrylist.Add(data1);
                }
                var arrylistjson = JsonConvert.SerializeObject(arrylist);
                if (typeName == FlowTypeName.flowsubmit)
                {
                    sql = "SELECT BizTableName FROM  `t_app_functionitem` WHERE CODE='" + formcode + "'";
                    string tablename = MySqlHelper.ExecuteScalar(CommandType.Text, sql, null).ToEmptyString();
                    sql = "SELECT RunningInstanceId from " + tablename + " where objectid='" + dataid + "'";
                    instanceid = MySqlHelper.ExecuteScalar(CommandType.Text, sql, null).ToEmptyString();
                }
                string flag = "";
                if (formType.ToUpper() == "NEW")
                {
                    flag = SaveFormInfo(ApiUrl,arrylistjson, dataid, formcode, creatuserid, typeName);
                }
                if (formType.ToUpper() == "EDIT")
                {
                    flag = submitForm_edit(ApiUrl,arrylistjson, dataid, formcode, creatuserid, instanceid, typeName);
                }
                return flag;
            }
        }

        public static string PostUrl(string url, string postData)
        {
            string result = "";
            try
            {
                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);

                req.Method = "POST";

                req.ContentType = "application/x-www-form-urlencoded;charset=utf-8";


                req.Timeout = 800;//请求超时时间

                byte[] data = Encoding.Default.GetBytes(postData);

                req.ContentLength = data.Length;

                using (Stream reqStream = req.GetRequestStream())
                {
                    reqStream.Write(data, 0, data.Length);

                    reqStream.Close();
                }

                HttpWebResponse resp = (HttpWebResponse)req.GetResponse();

                Stream stream = resp.GetResponseStream();

                //获取响应内容
                using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
                {
                    result = reader.ReadToEnd();
                }
                return result;
            }
            catch (Exception e)
            {
                return e.ToString();
            }
        }

        public static string GetUrl(string url)
        {
            try
            {
                Encoding encoding = Encoding.UTF8;
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = "GET";
                request.Accept = "text/html, application/xhtml+xml, */*";
                request.ContentType = "application/json";

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
                {
                    return reader.ReadToEnd();
                }
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
            
        }


        /// <summary>
        /// 将字符串转换成base64格式,使用UTF8字符集
        /// </summary>
        /// <param name="content">加密内容</param>
        /// <returns></returns>
        public static string Base64Encode(string content)
        {
            byte[] bytes = Encoding.UTF8.GetBytes(content);
            return Convert.ToBase64String(bytes);
        }

        /// <summary>  
        　/// Base64解密  
        　/// </summary>  
        　/// <param name="Message"></param>  
        　/// <returns></returns>  
        public static string Base64Decode(string content)
        {
            byte[] bytes = Convert.FromBase64String(content);
            return Encoding.Default.GetString(bytes);
        }
    }
}
